package com.dartsstats.datasource;

import java.util.Calendar;
import java.util.Date;

import com.dartsstats.Match;
import com.dartsstats.DM.MatchDM;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class MatchDataSource {

	private SQLiteDatabase database;
	private MatchDM matchDM;
	private String[] allColumns = { MatchDM.COLUMN_ID, MatchDM.COLUMN_AWAY_TEAM,  MatchDM.COLUMN_HOME_TEAM, MatchDM.COLUMN_SEASON_HALF, MatchDM.COLUMN_DATE};
	
	public MatchDataSource(Context context) {
		matchDM = new MatchDM(context);
	}
	
	public void open() throws SQLException {
		database = matchDM.getWritableDatabase();
	}
	
	public void close() {
		matchDM.close();
	}
	
	public Match createMatch(long awayTeam, long homeTeam, Date date, int seasonHalf){
		openDatabaseIfNull();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		ContentValues values = new ContentValues();
		values.put(MatchDM.COLUMN_AWAY_TEAM, awayTeam);
		values.put(MatchDM.COLUMN_HOME_TEAM, homeTeam);
		values.put(MatchDM.COLUMN_DATE, calendar.getTimeInMillis());
		values.put(MatchDM.COLUMN_SEASON_HALF, seasonHalf);
		long insertId = database.insert(MatchDM.TABLE_MATCH, null, values);
		Cursor cursor = database.query(MatchDM.TABLE_MATCH, allColumns, MatchDM.COLUMN_ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		Match match = cursorToMatch(cursor);
		cursor.close();
		return match;
	}
	
	public Match getMatchByID(int matchID) {
		openDatabaseIfNull();
		String[] whereArgs = new String[] {String.valueOf(matchID)};
		Cursor cursor = database.query(MatchDM.TABLE_MATCH, allColumns, MatchDM.COLUMN_ID + " = ?", whereArgs, null, null, null);
		cursor.moveToFirst();
		Match match = cursorToMatch(cursor);
		cursor.close();
		return match;
	}
	
	public void deleteMatch(Match match) {
		openDatabaseIfNull();
		long id = match.getId();
		System.out.println("Match deleted with id: " + id);
		database.delete(MatchDM.TABLE_MATCH, MatchDM.COLUMN_ID + " = " + id, null);
	}
	
	private Match cursorToMatch(Cursor cursor) {
		Match match = new Match();
		match.setId(cursor.getLong(0));
		match.setAwayTeam(cursor.getInt(1));
		match.setHomeTeam(cursor.getInt(2));
		match.setDate(new Date(cursor.getInt(3)));
		return match;
	}
	
	private void openDatabaseIfNull(){
		if(database==null){
			open();
		}
	}
}
